const { _ } = require('lodash');
const crypto = require("crypto-js");
const { now } = require('../util/util');
const { roles } = require('../conf/config');
const { encode, decode } = require('jwt-simple');
const { code, update } = require('../util/token');

const logger = require('tracer').dailyfile({ root: './logs', maxLogFiles: 10, allLogsFileName: 'system' });

module.exports = (app) => {
    app.use(async (ctx, next) => {
        app.context.code = app.context.code ? app.context.code : await code(app);

        try {
            const _TOKEN = ctx.cookies.get('token');
            if (_TOKEN && app.context.code) {
                const { fields: { page, rows } = { page: 0, rows: 0 } } = ctx.request;

                ctx.state.page = (page - 1) * rows;
                ctx.state.rows = rows;
                ctx.state.now = now;
                ctx.state.user = decode(_TOKEN, _.find(app.context.code, { sign: 'token' }).code);

                global.uuid = crypto.MD5(JSON.stringify(ctx.state.user)).toString();
                if (ctx.state.user.level == '1000') {
                    update(app, ctx.state.user);
                }
                await next();
                logger.log(global.uuid, ctx.ip, ',', JSON.stringify(ctx.state.user));
            }

        } catch (_err) {

            ctx.throw(_err);
        }
    });



}